<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input :placeholder="$t('table.name')" v-model="listQuery.name" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-select v-model="isAvailable" :placeholder="$t('table.available')" clearable style="width: 90px" class="filter-item">
        <el-option v-for="(item, index) in availableOptions" :key="index" :label="item.name" :value="item.value" />
      </el-select>
      <el-date-picker
                        v-model="listQuery.started_date"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="-"
                        :start-placeholder="$t('placeholder.start_date_from')"
                        :end-placeholder="$t('placeholder.start_date_to')"
                        value-format="yyyy-MM-dd">
                    </el-date-picker>
      <el-date-picker
                        v-model="listQuery.expiryed_date"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="-"
                        :start-placeholder="$t('placeholder.expiry_date_from')"
                        :end-placeholder="$t('placeholder.expiry_date_to')"
                        value-format="yyyy-MM-dd">
                    </el-date-picker>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleMulDelete">{{ $t('table.batch_delete') }}</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
      style="width: 100%;">
      <el-table-column
        type="selection"
        width="35">
      </el-table-column>
      <el-table-column :label="$t('table.id')" align="center" width="65">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.area')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.area_name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.name')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.curtitle }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column :label="$t('table.early_bird_fee_for_member')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.early_bird_fee_for_member }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column :label="$t('table.early_bird_fee_for_non_member')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.early_bird_fee_for_non_member }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column :label="$t('table.regular_fee')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.regular_fee }}</span>
        </template>
      </el-table-column> -->
      <el-table-column :label="$t('table.started_date')" width="160px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.started_date }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.expiryed_date')" width="160px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.expiryed_date }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.early_bird_date')" width="160px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.early_bird_date }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column :label="$t('table.created_at')" width="160px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column :label="$t('table.updated_at')" width="160px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updated_at }}</span>
        </template>
      </el-table-column> -->
      <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button size="mini" type="danger" @click="deleteData(scope.row)">{{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="900px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="margin-left:50px;">
        <el-form-item :label="$t('table.area')">
          <el-select v-model="temp.area" class="filter-item" placeholder="Please select">
            <el-option v-for="(item, index) in areaOptions" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.product_code')">
          <el-input v-model="temp.product_code" name="product_code" />
        </el-form-item>
		<el-form-item :label="$t('table.day')">
          <el-input v-model="temp.days" name="days" type="number" min="1" />
        </el-form-item>
        <el-form-item :label="$t('table.auto_renew')">
          <el-radio v-model="temp.auto_renew" label="1" name="auto_renew">{{ $t('table_element.auto_renew.on') }}</el-radio>
          <el-radio v-model="temp.auto_renew" label="0" name="auto_renew">{{ $t('table_element.auto_renew.off') }}</el-radio>
        </el-form-item>
        <el-form-item :label="$t('table.early_bird_fee_for_member')">
          <el-input v-model="temp.early_bird_fee_for_member" name="early_bird_fee_for_member" type="number"/>
        </el-form-item>
        <el-form-item :label="$t('table.early_bird_fee_for_non_member')">
          <el-input v-model="temp.early_bird_fee_for_non_member" name="early_bird_fee_for_non_member" type="number"/>
        </el-form-item>
        <el-form-item :label="$t('table.regular_fee')">
          <el-input v-model="temp.regular_fee" name="regular_fee" />
        </el-form-item>
        <el-form-item :label="$t('table.started_date')" required prop="started_date">
          <el-date-picker
            v-model="temp.started_date"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('placeholder.date')"/>
        </el-form-item>
        <el-form-item :label="$t('table.expiryed_date')" required prop="expiryed_date">
          <el-date-picker
            v-model="temp.expiryed_date"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('placeholder.date')"/>
        </el-form-item>
        <el-form-item :label="$t('table.early_bird_date')" required prop="early_bird_date">
          <el-date-picker
            v-model="temp.early_bird_date"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('placeholder.date')"/>
        </el-form-item>
        <el-form-item :label="$t('table.cleanse')">
          <el-radio v-model="temp.cleanse" label="1" name="cleanse">{{ $t('table_element.cleanse.on') }}</el-radio>
          <el-radio v-model="temp.cleanse" label="0" name="cleanse">{{ $t('table_element.cleanse.off') }}</el-radio>
        </el-form-item>
        <el-form-item :label="$t('table.group')">
          <el-select
            v-model="temp.group_id"
            :placeholder="$t('placeholder.select')"
            style="width: 560px;"
            multiple
            filterable
            allow-create
            default-first-option>
            <el-option
              v-for="(item, index) in groupList"
              :key="index"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.master_photo')">
          <!-- <el-upload
                  :show-file-list="false"
                  :on-success="handleImagesSuccess"
                  :action="getUploadImageUrl()"
                  class="avatar-uploader"
                  name = "img">
                  <el-button size="small" type="primary">{{$t('table.browse')}}</el-button>
                  <img v-if="temp.mphoto" :src="temp.mphoto" class="avatar">
            </el-upload> -->
          <el-upload
            :show-file-list="false"
            :auto-upload="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-change="changeFile"
            class="upload-demo"
            action="">
            <el-button size="small" type="primary">{{ $t('table.browse') }}</el-button>
            <img v-if="temp.mphoto" :src="temp.mphoto_url" class="avatar" style="width:80px; height:80px;">
          </el-upload>
        </el-form-item>
        <template>
          <el-tabs v-model="activeName" >
            <el-tab-pane label="en" name="first">
              <el-form-item :label="$t('table.title')" required prop="title">
                <el-input v-model="temp.title" name="title" />
              </el-form-item>
              <el-form-item :label="$t('table.description')" required prop="description">
                <el-input :rows="2" v-model="temp.description" type="textarea" :placeholder="$t('placeholder.input')"/>
              </el-form-item>
              <el-form-item :label="$t('table.content')">
                <tinymce id="fContent" :height="300" v-model="temp.content"/>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="zh-cn" name="second">
              <el-form-item :label="$t('table.title')">
                <el-input v-model="temp.cntitle" name="cntitle" />
              </el-form-item>
              <el-form-item :label="$t('table.description')">
                <el-input :rows="2" v-model="temp.cndescription" type="textarea" :placeholder="$t('placeholder.input')"/>
              </el-form-item>
              <el-form-item :label="$t('table.content')">
                <tinymce id="fCNContent" :height="300" v-model="temp.cncontent"/>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="zh-hk" name="third">
              <el-form-item :label="$t('table.title')">
                <el-input v-model="temp.hktitle" name="hktitle" />
              </el-form-item>
              <el-form-item :label="$t('table.description')">
                <el-input :rows="2" v-model="temp.hkdescription" type="textarea" :placeholder="$t('placeholder.input')"/>
              </el-form-item>
              <el-form-item :label="$t('table.content')">
                <tinymce id="fHKContent" :height="300" v-model="temp.hkcontent"/>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="zh-tw" name="fourth">
              <el-form-item :label="$t('table.title')">
                <el-input v-model="temp.twtitle" name="twtitle" />
              </el-form-item>
              <el-form-item :label="$t('table.description')">
                <el-input :rows="2" v-model="temp.twdescription" type="textarea" :placeholder="$t('placeholder.input')"/>
              </el-form-item>
              <el-form-item :label="$t('table.content')">
                <tinymce id="fTWContent" :height="300" v-model="temp.twcontent"/>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, fetchShow, fetchStore, fetchUpdate, fetchDelete, fetchBatchDelete } from '@/api/activity'
import { fetchUpimg } from '@/api/upload'
import waves from '@/directive/waves' // Waves directive
import { parseTime, getUploadImageUrl } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import Tinymce from '@/components/Tinymce'
import i18n from '@/lang/index'
import { fetchAll as fetchGroupAll } from '@/api/group'

export default {
  name: 'Tag',
  components: { Pagination, Tinymce },
  directives: { waves },
  filters: {
    availableFilter(status) {
      const availableMap = [
        'danger',
        'success'
      ]
      return availableMap[status]
    }
  },
  data() {
    return {
      //gggglobe: this.$store.state.locale.global, // store例子
      activeName: 'first',
      imageUrl: getUploadImageUrl(),
      isAvailable: 2,
      tableKey: 0,
      list: null,
      content: ``,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        available: 2,
        name: '',
        started_date: [],
        expiryed_date: [],
        lang: i18n.locale,
        area: this.$store.getters.area
      },
      groupList: [],
      activity_ids: [],
      availableOptions: [{ 'value': 2, 'name': i18n.t('table_element.available.all') }, { 'value': 1, 'name': i18n.t('table_element.available.on') }, {'value': 0, 'name': i18n.t('table_element.available.un') }],
      // areaOptions: [{ name : '中国香港', id: 1 }, { name : '中国大陆', id: 2 }],
      showReviewer: false,
      temp: {
        id: '',
        title: '',
        cntitle: '',
        hktitle: '',
        twtitle: '',
        content: '',
        cncontent: '',
        hkcontent: '',
        twcontent: '',
        description: '',
        cndescription: '',
        hkdescription: '',
        twdescription: '',
        product_code: '',
        auto_renew: '0',
        early_bird_fee_for_member: 0.00,
        early_bird_fee_for_non_member: 0.00,
        regular_fee: '0',
        cleanse: '0',
        started_date: '',
        expiryed_date: '',
        early_bird_date: '',
        group_id: [],
        mphoto: '',
        mphoto_url: '',
        area: 96,
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        title: [{ required: true, message: 'title is required', trigger: 'blur' }],
        description: [{ required: true, message: 'description  is required', trigger: 'blur' }],
        name: [{ required: true, message: 'name is required', trigger: 'blur' }],
        mphoto: [{ required: true, message: 'main photo is required', trigger: 'blur' }],
        master_photo: [{ required: true, message: 'main photo is required', trigger: 'blur' }],
        started_date: [{ required: true, message: 'started date is required', trigger: 'blur' }],
        expiryed_date: [{ required: true, message: 'expiryed date is required', trigger: 'blur' }],
        early_bird_date: [{ required: true, message: 'early bird date is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  computed: {
    areaOptions: function() {
      return this.$store.state.locale.areas
    }
  },
  created() {
    this.getList(),
    this.getGroupList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        // console.log(1989)
        var data = response.data
        this.list = data.data.data
        this.total = data.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: 'Update Success!​',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        cntitle: '',
        hktitle: '',
        twtitle: '',
        content: '',
        encontent: '',
        hkcontent: '',
        twcontent: '',
        description: '',
        cndescription: '',
        hkdescription: '',
        twdescription: '',
        product_code: '',
        auto_renew: '0',
        early_bird_fee_for_member: 0.00,
        early_bird_fee_for_non_member: 0.00,
        regular_fee: '0',
        cleanse: '0',
        started_date: '',
        expiryed_date: '',
        early_bird_date: '',
        group_id: [],
        area: 96,
        mphoto: '',
        mphoto_url:''
      }
    },
    handleCreate() {
      // store例子
      //let ll = ['cc', 'aa']
     // this.$store.dispatch('addLocale', ll)
     // this.gggglobe = this.$store.state.locale.global
     // console.log('global1', this.gggglobe)
      // store例子end
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        window.tinymce.get('fContent').setContent('')
        window.tinymce.get('fCNContent').setContent('')
        window.tinymce.get('fHKContent').setContent('')
        window.tinymce.get('fTWContent').setContent('')
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (this.temp.mphoto == '') {
          alert('main photo is required')
          return false;
        }

        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          this.temp.lang = i18n.locale
          fetchStore(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Create Success',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.auto_renew = this.temp.auto_renew.toString()
      this.temp.cleanse = this.temp.cleanse.toString()
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        window.tinymce.get('fContent').setContent(this.temp.content)
        window.tinymce.get('fCNContent').setContent(this.temp.cncontent)
        window.tinymce.get('fHKContent').setContent(this.temp.hkcontent)
        window.tinymce.get('fTWContent').setContent(this.temp.twcontent)
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (this.temp.mphoto == '') {
          alert('main photo is required')
          return false;
        }
        if (valid) {
          this.temp.lang = i18n.locale
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          fetchUpdate(this.temp.id, tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Success',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      console.log(row);
      this.$notify({
        title: 'Success',
        message: 'Delete Success',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    deleteData(row) {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        fetchDelete(row.id).then(response => {
          var data = response.data
          if (data.code == 0) {
            this.$notify({
              title: 'Success',
              message: 'Delete Success',
              type: 'success',
              duration: 2000
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          }

        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },
    handleMulDelete() {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        fetchBatchDelete({ activity_id: this.activity_ids }).then(response => {
          var data = response.data
          if (data.code == 0) {
            this.$notify({
              title: 'Success',
              message: 'Delete Success',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },
    handleSelectionChange(val) {
      val.forEach(element => {
        if (this.activity_ids.indexOf(element.id) == -1) {
          this.activity_ids.push(element.id)
        }
      })
    },
    getGroupList() {
      let params = {
        lang: i18n.locale,
                /* area: 96,
                name: '' */
      }
      fetchGroupAll(params).then((res) => {
      if (res.data.data.length > 0) {
          this.groupList = res.data.data
          // this.orderData.package = res.data.data[0]
          // this.changePackage()
        }
      })
    },
    handleAvatarSuccess(res, file) {
      this.temp.mphoto = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('Upload head picture can only be JPG!');
      }
      if (!isLt2M) {
        this.$message.error('The size of uploaded avatar pictures should not exceed 2MB');
      }
      return isJPG && isLt2M;
    },
    changeFile(file, fileList) {
      var This = this;
      // console.log(file)
      //this.imageUrl = URL.createObjectURL(file.raw);
      var reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = function(e){
          // this.result // 这个就是base64编码了
          This.imageUrl = this.result
          fetchUpimg({img: this.result}).then((res) => {
            if (res.data && res.data.data && res.data.data.paths && res.data.data.paths.length > 0) {
              This.temp.mphoto = res.data.data.paths[0].path // res.data.data.imageDomain + '/' +
              This.temp.imageDomain = res.data.data.imageDomain
              This.temp.mphoto_url = (res.data.data.paths[0].path.indexOf('http')==0) ? res.data.data.paths[0].path : res.data.data.imageDomain + '/' + res.data.data.paths[0].path
            }
          })
      }
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
